package com.lzs.adx.web.commmon.utils;

import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class URLParameterCleaner {

    // 正则表达式匹配占位符模式
// 更新正则表达式以匹配新的占位符模式
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("^(?:__.*__|_.*_|\\{.*\\}|\\$.*\\$)$");

    public static String cleanURL(String urlString)  {
        try {
            int queryIndex = urlString.indexOf('?');
            if (queryIndex == -1) {
                return urlString; // No query to clean
            }

            String baseUrl = urlString.substring(0, queryIndex);
            String query = urlString.substring(queryIndex + 1);
            Map<String, String> params = splitQuery(query);

            StringBuilder cleanedQuery = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!StringUtils.isEmpty(entry.getValue()) && !isPlaceholder(entry.getValue())) {
                    if (cleanedQuery.length() > 0) {
                        cleanedQuery.append("&");
                    }
                    cleanedQuery.append(URLEncoder.encode(entry.getKey(),"UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(),"UTF-8"));
                }
            }

            return baseUrl + "?" + cleanedQuery.toString();
        }catch (Exception e){
         e.printStackTrace();
         return null;
        }
    }

    private static Map<String, String> splitQuery(String query) {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            String key = pair.substring(0, idx);
            String value = pair.substring(idx + 1);
            queryPairs.put(key, value);
        }
        return queryPairs;
    }

    private static boolean isPlaceholder(String value) {
        return PLACEHOLDER_PATTERN.matcher(value).matches();
    }

    public static void main(String[] args) {
        try {
            String url = "https://api.vigorousxy.com/click?pid=1716&imei=__IMEI__&idfa=__IDFA__&idfa_md5=__IDFA_MD5__&caid=__CAID__&oaid=__OAID__&oaid_md5=__OAID_MD5__&androidid=__ANDROIDID__&request_id=__REQ_ID__&ip=__IP__&ua=__UA__&model=__MODEL__&callback=__CALLBACK__";
            String cleanedUrl = cleanURL(url);
            System.out.println("Cleaned URL: " + cleanedUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}